package com.guodi.model.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.core.tool.utils.Func;
import com.guodi.core.tool.utils.ObjectUtil;
import com.guodi.model.entity.ApiIdtFillTask;
import com.guodi.model.entity.IdtFillTask;
import com.guodi.model.entity.IdtFillTaskOpinion;
import com.guodi.model.vo.ApiIndicatorsFillTaskVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.guodi.core.tool.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import com.guodi.core.boot.ctrl.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

import com.guodi.model.service.IIdtFillTaskService;
import org.springframework.validation.annotation.Validated;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 指标填报任务表 前端控制器
 * 任务中心逻辑：
 * 1、由管理人员（具备indicator_admin角色）下发任务给各个地市填报，此时任务为待填报状态，例如admin用户；
 * 2、待填报状态，各个地市填报人员（具备indicator_reportor角色）进行填报，例如css2用户，填报完可以提交审核，此时任务为待审核状态；
 * 3、带审核状态，各个地市审核人员（具备indicator_check角色）进行任务审核，例如css1用户，审核结果为不通过时，任务回退为待填报状态；审核通过时，任务进入待评估状态；
 * 4、待评估状态，填报人员（具备indicator_reportor角色）进行专家意见填写，例如css2用户，填写完任务状态为已完成；
 *
 * @author lzy
 * @date 2023-05-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/IdtFillTask")
@Api(value = "API - IdtFillTaskController", tags = "指标填报任务表")
public class IdtFillTaskController extends BaseController {

    //默认当前年
    //private int currentYear = LocalDate.now().getYear();


    @Resource
    private IIdtFillTaskService iIdtFillTaskService;

    /**
     * @描述: 下发任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 14:22
     **/
    @RequestMapping("/iSSueTask")
    @ApiOperation(value = "下发任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "divisionCodes", value = "行政区划编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "截止时间", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "int", paramType = "query"),
    })
    public R iSSueTask(@ApiIgnore IdtFillTask task, String divisionCodes, Integer year) {
        String endTime = task.getEndTime();
        if (StringUtils.isBlank(endTime) || StringUtils.isBlank(divisionCodes)) {
            return R.fail("截止时间或行政区划编码必传");
        }
        if (ObjectUtil.isEmpty(year)) {
            year = LocalDate.now().getYear();
        }
        task.setYear(String.valueOf(year));
        String taskYear = task.getYear();

        List<String> divisions = new ArrayList<>();
        List<String> divisionList = Func.toStrList(",", divisionCodes);
        String regionCode = AuthUtil.getUser().getRegionCode();
        for (String division : divisionList) {
            if (!Objects.equals(division, regionCode)) {
                divisions.add(division);
            }
        }
        //判断是否已存在下发
        LambdaQueryWrapper<IdtFillTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTask::getYear, taskYear);
        wrapper.in(IdtFillTask::getDivisionCode, divisions);
        List<IdtFillTask> tasks = iIdtFillTaskService.list(wrapper);
        if (!CollectionUtils.isEmpty(tasks)) {
            List<String> collect = tasks.stream().map(x -> x.getDivisionName()).collect(Collectors.toList());
            return R.fail(StringUtils.join(collect, ",") + " 已存在填报任务，无需再次下发");
        }
        iIdtFillTaskService.iSSueTask(taskYear, divisions, endTime);
        return R.data("下发成功");
    }

    /**
     * @描述: 根据行政区级别统计任务各状态数量
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/22 15:03
     **/
    @RequestMapping("/listCountByCityLevel")
    @ApiOperation(value = "根据行政区级别统计任务各状态数量")
    public R listCountByCityLevel(Integer year) {
        if (ObjectUtil.isEmpty(year)) {
            year = LocalDate.now().getYear();
        }
        List list = this.iIdtFillTaskService.listCountByCityLevel(String.valueOf(year));
        return R.data(list);
    }


    /**
     * @描述: 任务进度总览
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 15:52
     **/
    @RequestMapping("/listByCondition")
    @ApiOperation(value = "任务进度总览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "页面大小，默认10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码，默认1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "地市级别[0：市级，1：区县，2：街道]", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "year", value = "年份,默认当前年份", dataType = "int", paramType = "query"),
    })
    public R listByCondition(@ApiIgnore Page page, String type, Integer year) {
        int codeLength = 0;
        switch (type) {
            case "0":
                codeLength = 4;
                break;
            case "1":
                codeLength = 6;
                break;
            case "2":
                codeLength = 9;
                break;
        }
        String yearParam = "";
        if (ObjectUtil.isNotEmpty(year)) {
            yearParam = String.valueOf(year);
        }
        IPage<ApiIdtFillTask> iPage = this.iIdtFillTaskService.listByCondition(page, yearParam, codeLength);
        return R.data(iPage);
    }

    /**
     * @描述: 待审核任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/22 16:26
     **/
    @RequestMapping("/AuditTask")
    @ApiOperation(value = "待审核任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "页面大小，默认10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码，默认1", dataType = "int", paramType = "query")
    })
    public R AuditTask(@ApiIgnore Page page) {
        IPage<IdtFillTask> iPage = this.iIdtFillTaskService.auditTask(page, null);
        return R.data(iPage);
    }

    /**
     * @描述: 已审核任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/22 16:26
     **/
    @RequestMapping("/CheckedTask")
    @ApiOperation(value = "已审核任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "页面大小，默认10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码，默认1", dataType = "int", paramType = "query")
    })
    public R CheckedTask(@ApiIgnore Page page) {
        IPage<IdtFillTask> iPage = this.iIdtFillTaskService.CheckedTask(page, null);
        return R.data(iPage);
    }


    /**
     * @描述: 待填报任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 17:25
     **/
    @RequestMapping("/waitFilledList")
    @ApiOperation(value = "待填报任务")
    @ApiImplicitParam(name = "year", value = "年份，默认当前年", dataType = "int", paramType = "query")
    public R waitFilledList(Integer year) {
        String taskYear = "";
        if (ObjectUtil.isEmpty(year)) {
            //year = LocalDate.now().getYear();
            taskYear = "";
        } else {
            taskYear = String.valueOf(year);
        }
        String regionCode = AuthUtil.getUserRegionCode();
        R r = iIdtFillTaskService.waitFilledList(taskYear, regionCode);
        return r;
    }

    /**
     * @描述: 待确认任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 17:25
     **/
    @RequestMapping("/waitConfirmList")
    @ApiOperation(value = "待确认任务")
    @ApiImplicitParam(name = "year", value = "年份，默认当前年", dataType = "int", paramType = "query")
    public R waitConfirmList(Integer year) {
        if (ObjectUtil.isEmpty(year)) {
            year = LocalDate.now().getYear();
        }
        String taskYear = String.valueOf(year);
        String regionCode = AuthUtil.getUserRegionCode();
        R r = iIdtFillTaskService.waitConfirmList(taskYear, regionCode);
        return r;
    }

    /**
     * @描述: 校验是否有提交按钮权限
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 17:25
     **/
    @RequestMapping("/verifySubmit")
    @ApiOperation(value = "校验是否有提交按钮权限")
    @ApiImplicitParam(name = "year", value = "年份，默认当前年", dataType = "int", paramType = "query")
    public R verifySubmit(Integer year) {
        if (ObjectUtil.isEmpty(year)) {
            year = LocalDate.now().getYear();
        }
        String taskYear = String.valueOf(year);
        String regionCode = AuthUtil.getUserRegionCode();
        LambdaUpdateWrapper<IdtFillTask> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(IdtFillTask::getYear, taskYear);
        wrapper.eq(IdtFillTask::getDivisionCode, regionCode);
        List<IdtFillTask> list = this.iIdtFillTaskService.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return R.data(false);
        }
        boolean flag = iIdtFillTaskService.verifySubmit(list.get(0));
        return R.data(flag);
    }

    /**
     * @描述: 待评估任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 17:25
     **/
    @RequestMapping("/estimateList")
    @ApiOperation(value = "待评估任务")
    public R estimateList(@ApiIgnore Page page) {
        String regionCode = AuthUtil.getUserRegionCode();
        IPage<IdtFillTask> iPage = iIdtFillTaskService.estimateList(page, null, regionCode);
        return R.data(iPage);
    }


    /**
     * @描述: 已办结任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/8 17:25
     **/
    @RequestMapping("/completedList")
    @ApiOperation(value = "已办结任务")
    public R completedList(@ApiIgnore Page page) {
        String regionCode = AuthUtil.getUserRegionCode();
        IPage<IdtFillTask> iPage = iIdtFillTaskService.completedList(page, null, regionCode);
        return R.data(iPage);
    }

    /**
     * @描述: 根据任务id获取相对应指标体系
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/9 10:49
     **/
    @RequestMapping("/getIndicatorsDirByTaskId")
    @ApiOperation(value = "根据任务id获取相对应指标体系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query")
    })
    public R getIndicatorsDirByTaskId(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return R.fail("任务id必传");
        }
        Map<String, List<ApiIndicatorsFillTaskVo>> map = iIdtFillTaskService.getIndicatorsDirByTaskId(taskId);
        return R.data(map);
    }

    /**
     * @描述: 确认任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/10 11:33
     **/
    @RequestMapping("/confirmByTaskId")
    @ApiOperation(value = "确认任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query")
    })
    public R confirmByTaskId(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return R.fail("任务id必传");
        }
        R r = iIdtFillTaskService.confirmByTaskId(taskId);
        return r;
    }

    /**
     * @描述: 驳回任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/10 11:44
     **/
    @RequestMapping("/rejectByTaskId")
    @ApiOperation(value = "驳回任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "message", value = "驳回意见", required = true, dataType = "string", paramType = "query")
    })
    public R rejectByTaskId(String taskId, String message) {
        if (StringUtils.isBlank(taskId)) {
            return R.fail("任务id必传");
        }
        if (StringUtils.isBlank(message)) {
            return R.fail("请填写驳回意见");
        }
        R r = iIdtFillTaskService.rejectByTaskId(taskId, message);
        return r;
    }

    /**
     * @描述: 催办任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/10 14:17
     **/
    @RequestMapping("/urgingByTaskId")
    @ApiOperation(value = "催办任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query")
    })
    public R urgingByTaskId(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return R.fail("任务id必传");
        }
        R r = iIdtFillTaskService.urgingByTaskId(taskId);
        return r;
    }


    /**
     * @描述: 提交任务
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/10 14:17
     **/
    @RequestMapping("/submitByTaskId")
    @ApiOperation(value = "提交任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query")
    })
    public R submitByTaskId(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return R.fail("任务id必传");
        }
        R r = iIdtFillTaskService.submitByTaskId(taskId);
        return r;
    }

    /**
     * @描述: 下载报告
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/24 14:19
     **/
    @RequestMapping("/downloadReportFile")
    @ApiOperation(value = "下载报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务id", required = true, dataType = "string", paramType = "query")
    })
    public R downloadReportFile(String taskId, HttpServletResponse response) {
        R r = this.iIdtFillTaskService.downloadReportFile(taskId, response);
        return r;
    }


    /**
     * @描述: 获取意见
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/31 17:48
     **/
    @RequestMapping("/getOptionsByTask")
    @ApiOperation(value = "获取意见")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划编码", required = true, dataType = "string", paramType = "query")
    })
    public R getOptionsByTask(String year, String divisionCode) {
        List<IdtFillTaskOpinion> opinions = this.iIdtFillTaskService.getOptionsByTask(year, divisionCode);
        return R.data(opinions);
    }


}
